#!/usr/bin/python
#
# Copyright (c) Citrix Systems 2008. All rights reserved.
#
# map serial numbers from scsi devices to device names
#

import os
import re
import subprocess

def doexec(args, inputtext=None):
    """Execute a subprocess, then return its return code, stdout and stderr"""
    proc = subprocess.Popen(args, stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 close_fds=True)
    (stdout, stderr) = proc.communicate(inputtext)
    retcode = proc.returncode
    return (retcode, stdout, stderr)

def pread(cmdlist):
    """ process read wrapper """
    cmdlist_for_exec = []
    cmdlist_for_log = []
    for item in cmdlist:
        if type(item) == type(""):
            cmdlist_for_exec.append(item)
            cmdlist_for_log.append(item)
        else:
            cmdlist_for_exec.append(item[0])
            cmdlist_for_log.append(item[1])

    (retcode, stdout, stderr) = doexec(cmdlist_for_exec)
    if retcode:
        raise
    return stdout

def match_sd(string):
    """ return sd* """
    regex = re.compile("^sd")
    return regex.search(string, 0)

def main():
    """ main entry for scsi checker """

    # get devices in /dev/sd*

    findser = "Unit serial number:"
    prefix = "/dev/"
    idlist = {}
    try:
        devlist = os.listdir(prefix)
        for name in filter(match_sd, devlist):
            filepath = prefix + name
            command = ["/usr/bin/sg_inq", filepath]
            try:
                retinfo = pread(command)
                index = retinfo.find(findser)
                if index != -1:
                    if idlist.has_key(retinfo[index+len(findser):len(retinfo)].strip()):
                        idlist[retinfo[index+len(findser):len(retinfo)].strip()].append(filepath)
                    else:
                        idlist[retinfo[index+len(findser):len(retinfo)].strip()]=[filepath]
            except:
                pass
    except:
        pass


    # get devices in /dev/disk/by-id/*
    
    prefix = "/dev/disk/by-id/"
    try:
        disklist = os.listdir(prefix)
        for name in disklist:
            filepath = prefix + name
            command = ["/usr/bin/sg_inq", filepath]
            try:
                retinfo = pread(command)
                index = retinfo.find(findser)
                if index != -1:
                    if idlist.has_key(retinfo[index+len(findser):len(retinfo)].strip()):
                        idlist[retinfo[index+len(findser):len(retinfo)].strip()].append(filepath)
                    else:
                        idlist[retinfo[index+len(findser):len(retinfo)].strip()]=[filepath]
            except:
                pass
    except:
        pass

    # get devices in /dev/mapper/*
    prefix = "/dev/mapper/"
    try:
        disklist = os.listdir(prefix)
        for name in disklist:
            filepath = prefix + name
            command = ["/usr/bin/sg_inq", filepath]
            try:
                retinfo = pread(command)
                index = retinfo.find(findser)
                if index != -1:
                    if idlist.has_key(retinfo[index+len(findser):len(retinfo)].strip()):
                        idlist[retinfo[index+len(findser):len(retinfo)].strip()].append(filepath)
                    else:
                        idlist[retinfo[index+len(findser):len(retinfo)].strip()]=[filepath]
            except:
                pass
    except:
        pass

    for id in idlist:
        print
        print "serial number '%s' maps the following devices " % id
        for mapping in idlist[id]:
            print "            %s" % mapping
    print 

if __name__ == "__main__":
    main()
